package cn.newgrand.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    private static char[] hexChar = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    
    public static String calcMDFive(File file,String hashType) throws NoSuchAlgorithmException, IOException{
   	 InputStream in = new FileInputStream(file);
   	 byte[] buffer = new byte[1024];
   	 MessageDigest md5 = MessageDigest.getInstance(hashType);
   	 int numRead = 0;
   	 while((numRead = in.read(buffer))>0){
   		 md5.update(buffer, 0, numRead);
   	 }
   	 in.close();
   	 return toHexString(md5.digest());
    }
    
    private static String toHexString(byte[] b){
   	 StringBuilder sb = new StringBuilder(b.length*2);
   	 for(int i=0;i<b.length;i++){
   		 sb.append(hexChar[(b[i]&0xf0)>>>4]);
   		 sb.append(hexChar[b[i]&0x0f]);
   	 }
   	 return sb.toString();
    }
}
